package Application.Config;

import Application.Exceptions.AppExceptions;
import Application.Util.StaticUtil;
import Application.MethodObject.DefTings;
import Application.Others.AI_Talk_And_Favorability;
import Application.Widgets.ErrorReportWidget;

import java.awt.*;
import java.io.*;
import java.util.ArrayList;

public class Config implements Serializable {
    private static final long serialVersionUID = 2906642554793891381L;
    public static final File configFile = new File("config.cfg");

    public AI_Talk_And_Favorability AI = new AI_Talk_And_Favorability();
    private int fontNum = 0;
    public ArrayList<Font> fonts = new ArrayList<>();
    public Font font_1 = new Font("MS Song", Font.PLAIN, 15);//宋体
    public Font font_2 = new Font("仿宋", Font.PLAIN, 15);//仿宋
    public final DefTings def = new DefTings();
    public File default_open_path = new File(def.XAMLName);
    public File background_file = null;

    public Config() {
        fonts.add(font_1);
        fonts.add(font_2);
    }

    public Font fontGetter() {
        return fonts.get(fontNum);
    }

    public void fontNumSetter(int f) throws AppExceptions {
        if (f >= 0 & f <= 1) {
            fontNum = f;
        } else {
            throw new AppExceptions(StaticUtil.ErrNum_Wrong_Parameter);
        }
    }

    public static void configWriter(Config c)
    {
        try {
            ObjectOutputStream OS;
            OS = new ObjectOutputStream(new FileOutputStream(configFile));
            OS.writeObject(c);
            OS.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static Config configReader() {
        if (configFile.exists())
        {
            try {
                ObjectInputStream IS;
                IS = new ObjectInputStream(new FileInputStream(configFile));
                Object o = IS.readObject();
                if (o != null) {
                    return  (Config) o;
                }
                IS.close();
            } catch (EOFException | StreamCorruptedException e) {
                e.printStackTrace();
                Config.configWriter(new Config());
                ErrorReportWidget.errorReport.append(
                        e.getMessage()+
                        "\n"+
                        new AppExceptions(2).ErrGetter()+"\n"+
                        "AI：放心，我已经帮你清除错误啦。\n");
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        return new Config();

    }
}